(function ($) {
	var rowid = ''
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	function baseSetup(){
		// plus.navigator.setStatusBarStyle('light');
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		var self = plus.webview.currentWebview()
		rowid = self.row||""
		if (rowid != "") {
			getDetailData()
		}
		// plus.webview.currentWebview().setStyle({titleNView: {titleText: 'new text'}})
		$('.posBtn').on('tap', 'button', function(e) {
			//console.log(this.getAttribute('position'))
			if(!this.classList.contains('selected')){
				$('.posBtn button').each( function(){
					this.classList.remove('selected')
				})
				this.classList.add('selected')
			}
		})
		
		$('.levelBtn').on('tap', 'button', function(e) {
			//console.log(this.getAttribute('level'))
			if(!this.classList.contains('selected')){
				$('.levelBtn button').each( function(){
					this.classList.remove('selected')
					this.removeAttribute('style')
				})
				this.classList.add('selected')
				var color = this.getAttribute('data-color')
				if (color && color!="") {
					this.style.color =color
					this.style.borderColor = color
				}
			}
		})
		//选择时间
		$click("dtpick", function() {
			var _self = this;
			if(_self.picker) {
				_self.picker.show(function (rs) {
					$setText('#sendTime',rs.text + ':00')
					_self.picker.dispose();
					_self.picker = null;
				});
			} else {
				var optionsJson = this.getAttribute('data-options') || '{}';
				var options = JSON.parse(optionsJson);
				var id = this.getAttribute('id');
				_self.picker = new $.DtPicker(options);
				_self.picker.show(function(rs) {
					 $setText('#sendTime',rs.text + ':00')
					_self.picker.dispose();
					_self.picker = null;
				});
			}
		})
		//选择对象
		$click("objPick", function() {
			getWardList(true)
			//改为选择病区--与PC端保持一致
			return
			var url = 'objPick.html';
			var webviewId = 'objPick.html';
			webview = plus.webview.create(url, webviewId, {
				titleNView: {
					backgroundColor: '#fff',
					titleText: '选择对象',
					titleSize: '18px',
					titleColor: '#1D2334',
					autoBackButton: true,
				}
			},{});
			webview.show()
		})
		$click("filePick", function() {
			mui.toast('添加附件功能完善中');
			return
		})
		// 保存
		$click("save", function() {
			requestData('N','保存');
		})
		// 发布
		$click("send", function() {
			requestData('Y','发布');
		})
		mui('#wardPopo').on('tap','.wardCloseBtn',function(){
			mui('#wardPopo').popover('toggle')
		})
		mui('#wardPopo').on('tap','.wardSureBtn',function(){
			var ids = ''
			var text = ''
			mui('#wardPopo li.dhc-active').each(function (index,element) {
				if (ids != '') {
					ids += ','
					text += ','
				}
				ids += element.getAttribute('data-id')
				text += element.innerText
			})
			$('#sendObj')[0].innerText = text
			$('#sendObj')[0].setAttribute('data-id',ids)
			mui('#wardPopo').popover('toggle')
		})
		mui('#wardUL').on('tap','li',function(){
			var classStr = this.getAttribute('class')
			if (classStr.indexOf('dhc-active') != -1) {
				this.classList.remove('dhc-active')
			}else{
				this.classList.add('dhc-active')
			}
		}) 
		getLevelData()
		getWardList()
		//选择通知人员
		mui('#groupCode').on('tap','button',function(){
			if (this.getAttribute('class').indexOf('dhc-active') != -1) {
				this.classList.remove('dhc-active')
			}else{
				this.classList.add('dhc-active')
			}
		}) 
		//refer/pf/WorkNotice/5 success:Fileupdate/refer/pf/WorkNotice/5/技操打分-A是否模式.txt
	}
	function getDetailData(){
		var pdict = {'rw':rowid,'flag':'0'}
		console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMPlatform:GetWorkNotice','params':JSON.stringify(pdict),'type':'RecMethod'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msgcode'] == '1') {
				var dataDict = result['data']
				$('#title')[0].value = dataDict['NoticeTitle'];
				var NoticeContext = dataDict['NoticeContext']||''
				NoticeContext = NoticeContext.replace(/☼/g, "\"")
				NoticeContext = NoticeContext.replace(/\\/g,"")
				// NoticeContext = NoticeContext.replace(/@l@/g, '<');
				// NoticeContext = NoticeContext.replace(/@r@/g, '>');
				// NoticeContext = NoticeContext.replace(/&lt;/g, '<');
				// NoticeContext = NoticeContext.replace(/&gt;/g, '>');
				// NoticeContext = NoticeContext.replace(/&amp;/g, '&');
				$('#editBody')[0].innerHTML = NoticeContext;
				var NoticeLevel = dataDict.NoticeLevel
				if (NoticeLevel!="") {
					var levelBtn = $('#level button[level="'+dataDict.NoticeLevel+'"]')[0]
					if (levelBtn) {
						mui.trigger(levelBtn,'tap')
					}else{
						$('#level')[0].setAttribute('level',dataDict.NoticeLevel);
					}
				}
				
				$('#sendTime')[0].innerText = dataDict.NoticeDate + ' ' + dataDict.NoticeTime;
				var NoticeWard = dataDict.NoticeWard
				if (NoticeWard!= "") {
					var wardDesc = ''
					var wardArr = NoticeWard.split(',')
					for (var i = 0; i < wardArr.length; i++) {
						var dom = $('#wardUL li[data-id="'+wardArr[i]['rw']+'"]')[0]
						if (dom) {
							dom.classList.add('dhc-active')
							if (wardDesc != "") {
								wardDesc += ','
							}else{
								wardDesc += dom.innerText
							}
						}
					}
					$('#sendObj')[0].innerText = wardDesc
					$('#sendObj')[0].setAttribute('data-id',NoticeWard)
				}
				var groups = dataDict.NoticeGroup||''
				var arr = groups.split(';')
				mui.each(arr,function (index,str) {
					if (str != '') {
						var dom = mui('button[data-id="'+str+'"]')[0]
						if (dom) {
							dom.classList.add('mui-active')
						}
					}
				})
			}else{
				mui.toast(result.msg)
			}
			plus.nativeUI.closeWaiting()
		}, function(errorStr) {
			plus.nativeUI.closeWaiting()
			mui.toast(errorStr)
		});
	}
	
	function getLevelData(){
		var pdict = {'type': '消息等级'}
		var paramDict = {'method':'web.INMDBComm:FindPubCode','params':JSON.stringify(pdict),'type':'Query'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result.msgcode == '1') {
				var dataArr = result['data']
				var html = ''
				var detailLevel = $('#level')[0].getAttribute('level')||""
				for (var i = 0; i < dataArr.length; i++) {
					var dict = dataArr[i]
					var select = ''
					var color=dict['SubColor']||""
					if (detailLevel == dict['SubValue']) {
						select = 'selected" style="color:'+color+';border-color:'+color+';'
					}
					html+='<button level="'+dict['SubValue']+'" data-color="'+color+'" class="mui-btn '+select+'">'+dict['SubDesc']+'</button>'
				}
				$('#level')[0].innerHTML = html
				if (dataArr.length > 0 && detailLevel=="") {
					var lastDom = $('#level button')[dataArr.length-1]
					mui.trigger(lastDom,'tap')
				}
				
			}else{
				plus.nativeUI.closeWaiting()
			}
		}, function(errorStr) {
			
			plus.nativeUI.closeWaiting()
		});
	}
	function getWardList(show){
		if (show) {
			if ($('#wardUL li')[0]) {
				mui('#wardPopo').popover('toggle')
				return
			}
			plus.nativeUI.showWaiting('正在加载...', {modal: false})
		}
		var user = app.getState()
		var pdict = {'start':0,'nurseid':user.loginID,'limit':''}
		user = null
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMDataLimit:FindRoleWardList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msgcode'] == '1') {
				var wardArr = result['data']
				var html = '',wardDesc = ''
				var detailWard = ','+($('#sendObj')[0].getAttribute('data-id')||'')+','
				for (var i = 0; i < wardArr.length; i++) {
					var oneWard = wardArr[i]
					var wardid = ','+oneWard['rw']+','
					var active = ''
					if (detailWard.indexOf(wardid) != -1) {
						active = 'dhc-active'
						if (wardDesc !='') {
							wardDesc +=','
						}
						wardDesc += oneWard['WardDesc']
					}
					html += '<li class="mui-table-view-cell '+active+'" data-id="'+oneWard['rw']+'">'+oneWard['WardDesc']+'</li>'
				}
				$('#wardUL')[0].innerHTML = html;
				$('#sendObj')[0].innerText = wardDesc
				if (show) {
					mui('#wardPopo').popover('toggle')
				}
			}else if(show){
				mui.toast(result.msg)
			}
			plus.nativeUI.closeWaiting()
		}, function(errorStr) {
			plus.nativeUI.closeWaiting()
			mui.toast(errorStr)
		});
	}

	function requestData(flag,tip){
		const user = app.getState()
		var title = $('#title')[0].value;
		var context = $('#editBody')[0].innerHTML;
		context = context.replace(/\"/g, "☼")
		//var context = context.replace(/\//g, "\/")
		context = context.replace(/\\/g, '');
		context = context.replace(/&/g, '&amp;');
		context = context.replace(/</g, '&lt;');
		context = context.replace(/>/g, '&gt;');
		var level = ''
		if ($('#level .mui-btn.selected')[0]) {
			level = $('#level .mui-btn.selected')[0].getAttribute('level')
		}
		var dateTimeStr = $('#sendTime')[0].innerText
		var date = '',time = ''
		if (dateTimeStr.length > 10) {
			date = dateTimeStr.substring(0,10);
			time = dateTimeStr.slice(11);
		}
		if(title == ''){
			alert('请输入公告的标题！')
			return
		}
		if(date==""){
			alert('请选择发布时间！')
			return
		}
		if (level == '') {
			alert('请选择级别！')
			return
		}
		var group = ''
		mui('#groupCode button.dhc-active').each(function (index,element) {
			if (group != '') {
				group += ';'
			}
			group += element.getAttribute('data-id')
		})
		
		var wards=$('#sendObj')[0].getAttribute('data-id')||""
		var str = 'NoticeStatus|'+flag+'^NoticeTitle|'+title+'^NoticeLevel|'+level+
					'^NoticeDate|'+date+'^NoticeTime|'+time+'^NoticeWard|'+wards+'^NoticeCreator|^rw|'+rowid+
					'^NoticeGroup|'+group
		var arg = {
			parr: str,
			context:context,
			APPLoginID: user.loginID,
			APPPerID: user.loginPerID,
			loginID: user.loginID
		}
		console.log(JSON.stringify(arg))
		// return
		var paramDict = {
			'method': 'web.INMPlatform:SaveWorkNotice',
			'params': JSON.stringify(arg),
			'type': 'Method'
		}
		plus.nativeUI.showWaiting('正在'+tip+'...', {modal: false})
		$.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			//console.log(JSON.stringify(result))
			if (result.msgcode == '-1') {
				$.toast(result.msg);
			}else{
				$.toast(tip + '成功');
				plus.webview.currentWebview().close()
			}
		}, function(errorStr) {
			plus.nativeUI.closeWaiting();
			console.log(errorStr)
			$.toast(tip + '错误');
		});
		
		var parentHtml = plus.webview.getWebviewById('announceList.html');
		if(parentHtml){
			parentHtml.evalJS("refreshData('"+'3'+"')");
		}
	}
	
})(mui);

function sendAnnounce(){
	alert('发送成功');
}